from datetime import datetime
from . import db
from .models import User, Intersection, OptimizationRecord, AIAnalysis, SystemLog
from .utils import parse_json_data, format_json_data

class UserService:
    """用户服务类"""
    
    @staticmethod
    def authenticate(username, password):
        """用户认证"""
        user = User.query.filter_by(username=username).first()
        if user and user.check_password(password):
            return user
        return None
    
    @staticmethod
    def get_user_by_id(user_id):
        """根据ID获取用户"""
        return User.query.get(user_id)
    
    @staticmethod
    def get_user_by_username(username):
        """根据用户名获取用户"""
        return User.query.filter_by(username=username).first()

class IntersectionService:
    """路口数据服务类"""
    
    @staticmethod
    def get_intersections(page=1, per_page=10, keyword='', start_date=None, end_date=None):
        """获取路口数据列表"""
        query = Intersection.query
        
        # 搜索过滤
        if keyword:
            query = query.filter(
                db.or_(
                    Intersection.name.ilike(f'%{keyword}%'),
                    Intersection.location.ilike(f'%{keyword}%')
                )
            )
        
        # 日期范围过滤
        if start_date:
            query = query.filter(Intersection.created_at >= datetime.strptime(start_date, '%Y-%m-%d'))
        if end_date:
            query = query.filter(Intersection.created_at <= datetime.strptime(end_date, '%Y-%m-%d'))
        
        # 排序
        query = query.order_by(Intersection.created_at.desc())
        
        # 分页
        pagination = query.paginate(page=page, per_page=per_page, error_out=False)
        
        return {
            'items': [item.to_dict() for item in pagination.items],
            'total': pagination.total,
            'pages': pagination.pages,
            'current_page': page
        }
    
    @staticmethod
    def get_intersection_by_id(intersection_id):
        """根据ID获取路口数据"""
        return Intersection.query.get(intersection_id)
    
    @staticmethod
    def create_intersection(data):
        """创建路口数据"""
        intersection = Intersection(
            name=data.get('name'),
            type=data.get('type'),
            location=data.get('location'),
            lane_count=data.get('lane_count'),
            signal_config=data.get('signal_config'),
            peak_hours=data.get('peak_hours'),
            avg_traffic=data.get('avg_traffic'),
            accident_records=data.get('accident_records'),
            surrounding_facilities=data.get('surrounding_facilities')
        )
        
        db.session.add(intersection)
        db.session.commit()
        
        return intersection
    
    @staticmethod
    def update_intersection(intersection_id, data):
        """更新路口数据"""
        intersection = Intersection.query.get(intersection_id)
        if not intersection:
            return None
            
        intersection.name = data.get('name', intersection.name)
        intersection.type = data.get('type', intersection.type)
        intersection.location = data.get('location', intersection.location)
        intersection.lane_count = data.get('lane_count', intersection.lane_count)
        intersection.signal_config = data.get('signal_config', intersection.signal_config)
        intersection.peak_hours = data.get('peak_hours', intersection.peak_hours)
        intersection.avg_traffic = data.get('avg_traffic', intersection.avg_traffic)
        intersection.accident_records = data.get('accident_records', intersection.accident_records)
        intersection.surrounding_facilities = data.get('surrounding_facilities', intersection.surrounding_facilities)
        intersection.updated_at = datetime.utcnow()
        
        db.session.commit()
        
        return intersection
    
    @staticmethod
    def delete_intersection(intersection_id):
        """删除路口数据"""
        intersection = Intersection.query.get(intersection_id)
        if not intersection:
            return False
            
        db.session.delete(intersection)
        db.session.commit()
        
        return True

class OptimizationRecordService:
    """优化记录服务类"""
    
    @staticmethod
    def get_optimization_records(page=1, per_page=10, keyword='', start_date=None, end_date=None):
        """获取优化记录列表"""
        query = OptimizationRecord.query
        
        # 搜索过滤
        if keyword:
            query = query.filter(
                db.or_(
                    OptimizationRecord.content.ilike(f'%{keyword}%'),
                    OptimizationRecord.optimizer.ilike(f'%{keyword}%')
                )
            )
        
        # 日期范围过滤
        if start_date:
            query = query.filter(OptimizationRecord.created_at >= datetime.strptime(start_date, '%Y-%m-%d'))
        if end_date:
            query = query.filter(OptimizationRecord.created_at <= datetime.strptime(end_date, '%Y-%m-%d'))
        
        # 排序
        query = query.order_by(OptimizationRecord.created_at.desc())
        
        # 分页
        pagination = query.paginate(page=page, per_page=per_page, error_out=False)
        
        return {
            'items': [item.to_dict() for item in pagination.items],
            'total': pagination.total,
            'pages': pagination.pages,
            'current_page': page
        }
    
    @staticmethod
    def get_optimization_record_by_id(record_id):
        """根据ID获取优化记录"""
        return OptimizationRecord.query.get(record_id)
    
    @staticmethod
    def create_optimization_record(data):
        """创建优化记录"""
        record = OptimizationRecord(
            optimize_date=datetime.strptime(data.get('optimize_date'), '%Y-%m-%d').date() if data.get('optimize_date') else None,
            optimizer=data.get('optimizer'),
            content=data.get('content'),
            effect=data.get('effect'),
            before_data=format_json_data(data.get('before_data')),
            after_data=format_json_data(data.get('after_data'))
        )
        
        db.session.add(record)
        db.session.commit()
        
        return record
    
    @staticmethod
    def update_optimization_record(record_id, data):
        """更新优化记录"""
        record = OptimizationRecord.query.get(record_id)
        if not record:
            return None
            
        if data.get('optimize_date'):
            record.optimize_date = datetime.strptime(data.get('optimize_date'), '%Y-%m-%d').date()
        record.optimizer = data.get('optimizer', record.optimizer)
        record.content = data.get('content', record.content)
        record.effect = data.get('effect', record.effect)
        if 'before_data' in data:
            record.before_data = format_json_data(data.get('before_data'))
        if 'after_data' in data:
            record.after_data = format_json_data(data.get('after_data'))
        record.updated_at = datetime.utcnow()
        
        db.session.commit()
        
        return record
    
    @staticmethod
    def delete_optimization_record(record_id):
        """删除优化记录"""
        record = OptimizationRecord.query.get(record_id)
        if not record:
            return False
            
        db.session.delete(record)
        db.session.commit()
        
        return True

class AIAnalysisService:
    """AI分析服务类"""
    
    @staticmethod
    def get_ai_analyses(page=1, per_page=10, keyword='', start_date=None, end_date=None):
        """获取AI分析历史列表"""
        query = AIAnalysis.query
        
        # 搜索过滤
        if keyword:
            query = query.filter(
                db.or_(
                    AIAnalysis.intersection_name.ilike(f'%{keyword}%'),
                    AIAnalysis.result_summary.ilike(f'%{keyword}%')
                )
            )
        
        # 日期范围过滤
        if start_date:
            query = query.filter(AIAnalysis.created_at >= datetime.strptime(start_date, '%Y-%m-%d'))
        if end_date:
            query = query.filter(AIAnalysis.created_at <= datetime.strptime(end_date, '%Y-%m-%d'))
        
        # 排序
        query = query.order_by(AIAnalysis.created_at.desc())
        
        # 分页
        pagination = query.paginate(page=page, per_page=per_page, error_out=False)
        
        return {
            'items': [item.to_dict() for item in pagination.items],
            'total': pagination.total,
            'pages': pagination.pages,
            'current_page': page
        }
    
    @staticmethod
    def get_ai_analysis_by_id(analysis_id):
        """根据ID获取AI分析记录"""
        return AIAnalysis.query.get(analysis_id)
    
    @staticmethod
    def create_ai_analysis(data):
        """创建AI分析记录"""
        analysis = AIAnalysis(
            intersection_id=data.get('intersection_id'),
            intersection_name=data.get('intersection_name'),
            period=data.get('period'),
            goals=format_json_data(data.get('goals')),
            result_summary=data.get('result_summary'),
            problems=format_json_data(data.get('problems')),
            suggestions=format_json_data(data.get('suggestions')),
            expected_effects=format_json_data(data.get('expected_effects')),
            confidence_score=data.get('confidence_score'),
            analysis_time=data.get('analysis_time')
        )
        
        db.session.add(analysis)
        db.session.commit()
        
        return analysis
    
    @staticmethod
    def update_ai_analysis(analysis_id, data):
        """更新AI分析记录"""
        analysis = AIAnalysis.query.get(analysis_id)
        if not analysis:
            return None
            
        analysis.intersection_id = data.get('intersection_id', analysis.intersection_id)
        analysis.intersection_name = data.get('intersection_name', analysis.intersection_name)
        analysis.period = data.get('period', analysis.period)
        if 'goals' in data:
            analysis.goals = format_json_data(data.get('goals'))
        analysis.result_summary = data.get('result_summary', analysis.result_summary)
        if 'problems' in data:
            analysis.problems = format_json_data(data.get('problems'))
        if 'suggestions' in data:
            analysis.suggestions = format_json_data(data.get('suggestions'))
        if 'expected_effects' in data:
            analysis.expected_effects = format_json_data(data.get('expected_effects'))
        analysis.confidence_score = data.get('confidence_score', analysis.confidence_score)
        analysis.analysis_time = data.get('analysis_time', analysis.analysis_time)
        analysis.updated_at = datetime.utcnow()
        
        db.session.commit()
        
        return analysis
    
    @staticmethod
    def delete_ai_analysis(analysis_id):
        """删除AI分析记录"""
        analysis = AIAnalysis.query.get(analysis_id)
        if not analysis:
            return False
            
        db.session.delete(analysis)
        db.session.commit()
        
        return True

class DashboardService:
    """仪表板服务类"""
    
    @staticmethod
    def get_stats():
        """获取系统统计信息"""
        intersection_count = Intersection.query.count()
        optimization_record_count = OptimizationRecord.query.count()
        ai_analysis_count = AIAnalysis.query.count()
        
        return {
            'intersection_count': intersection_count,
            'optimization_record_count': optimization_record_count,
            'ai_analysis_count': ai_analysis_count
        }
    
    @staticmethod
    def get_recent_activities(limit=10):
        """获取最近活动记录"""
        # 合并所有记录并按时间排序
        all_activities = []
        
        # 路口数据记录
        intersections = Intersection.query.order_by(Intersection.created_at.desc()).limit(5).all()
        for intersection in intersections:
            all_activities.append({
                'time': intersection.created_at.isoformat() if intersection.created_at else '',
                'content': f'新增路口数据 - {intersection.name}',
                'user': '管理员',
                'type': 'intersection'
            })
        
        # 优化记录
        optimization_records = OptimizationRecord.query.order_by(OptimizationRecord.created_at.desc()).limit(5).all()
        for record in optimization_records:
            all_activities.append({
                'time': record.created_at.isoformat() if record.created_at else '',
                'content': f'录入优化记录 - {record.content[:20]}...',
                'user': record.optimizer,
                'type': 'optimization'
            })
        
        # AI分析记录
        ai_analyses = AIAnalysis.query.order_by(AIAnalysis.created_at.desc()).limit(5).all()
        for analysis in ai_analyses:
            all_activities.append({
                'time': analysis.created_at.isoformat() if analysis.created_at else '',
                'content': f'完成AI分析 - {analysis.intersection_name}',
                'user': '管理员',
                'type': 'ai_analysis'
            })
        
        # 按时间排序
        all_activities.sort(key=lambda x: x['time'], reverse=True)
        
        # 取最近的记录
        recent_activities = all_activities[:limit]
        
        return recent_activities

class LogService:
    """日志服务类"""
    
    @staticmethod
    def add_log(level, module, message, user=None):
        """添加系统日志"""
        log = SystemLog(
            level=level,
            module=module,
            message=message,
            user=user
        )
        
        db.session.add(log)
        db.session.commit()
        
        return log
    
    @staticmethod
    def get_logs(page=1, per_page=10, level=None, keyword=None):
        """获取系统日志列表"""
        query = SystemLog.query
        
        # 根据日志级别筛选
        if level:
            query = query.filter(SystemLog.level == level)
        
        # 根据关键字筛选
        if keyword:
            query = query.filter(
                db.or_(
                    SystemLog.message.ilike(f'%{keyword}%'),
                    SystemLog.module.ilike(f'%{keyword}%'),
                    SystemLog.user.ilike(f'%{keyword}%')
                )
            )
        
        # 按时间倒序排列
        query = query.order_by(SystemLog.timestamp.desc())
        
        # 分页
        pagination = query.paginate(page=page, per_page=per_page, error_out=False)
        
        return {
            'items': [item.to_dict() for item in pagination.items],
            'total': pagination.total,
            'pages': pagination.pages,
            'current_page': page
        }
    
    @staticmethod
    def delete_log(log_id):
        """删除系统日志"""
        log = SystemLog.query.get(log_id)
        if not log:
            return False
            
        db.session.delete(log)
        db.session.commit()
        
        return True
    
    @staticmethod
    def clear_logs():
        """清空系统日志"""
        SystemLog.query.delete()
        db.session.commit()
        
        return True